package com.augurit.gzcgwsp.sendNotice.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.augurit.common.syscode.service.ISysCodeService;
import com.augurit.common.syscode.web.form.SysCodeForm;
import com.augurit.common.syslog.tool.SysTraceLogWriter;
import com.augurit.common.util.lang.DateUtils;
import com.augurit.gzcgwsp.commonex.util.lang.StringUtilsEX;
import com.augurit.gzcgwsp.sendNotice.entity.YwWebserviceInfo;
import com.augurit.gzcgwsp.sendNotice.service.ICreateNoticeCommonPartService;
import com.augurit.gzcgwsp.sendNotice.service.IYwWebserviceInfoService;
import com.augurit.gzcgwsp.ssgd.web.form.YwRqSsgdSqbForm;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.common.dao.WfBusInstanceDao;

@Service
@Transactional
public class CreateNoticeCommonPartServiceImpl implements ICreateNoticeCommonPartService {
	private static final Logger logger = Logger.getLogger(CreateNoticeCommonPartServiceImpl.class);
	@Autowired
	private IYwWebserviceInfoService ywWebserviceInfoService;
	@Autowired
    private ISysCodeService syscodeService;

	private Map<String, String> noticeLabelMap;// 通知的标签
	@Autowired
	private  WfBusInstanceDao wfBusInstanceDao;
	
	/**
	 * 产生案件公示表html文件
	 * @param YwRqSsgdSqbForm
	 * @return 
	 * @throws IOException 
	 */
	public void createHtml(YwRqSsgdSqbForm ywRqSsgdSqbForm) throws IOException{
		String ssgdmc = ywRqSsgdSqbForm.getSsgdmc();//公示项目名称
		if(StringUtils.isEmpty(ssgdmc)){
			ssgdmc = "";
		}
		String address = ywRqSsgdSqbForm.getAddress();//项目地点
		if(StringUtils.isEmpty(address)){
			address = "";
		}
		String itemCode = ywRqSsgdSqbForm.getSsxzqy();//所属行政区域
		List<SysCodeForm> ywRqssgdQy = syscodeService.getItems("YW_RQSSGD_QY");
    	String itemName = "";
    	for(int i= 0 ;i<ywRqssgdQy.size();i++){
    		SysCodeForm sysCodeForm =  ywRqssgdQy.get(i);
    		if((sysCodeForm.getItemCode()).equals(itemCode)){
    			itemName = sysCodeForm.getItemName();
    		}
    	}
		String gdzynr = ywRqSsgdSqbForm.getGdzynr();//项目主要内容
		if(StringUtils.isEmpty(gdzynr)){
			gdzynr = "";
		}
		String ssgdyy = ywRqSsgdSqbForm.getSsgdyy();//设施改动原因
		if(StringUtils.isEmpty(ssgdyy)){
			ssgdyy = "";
		}
		Date jhsssj = ywRqSsgdSqbForm.getJhsssj();//计划开工时间
		Date jhwcsj = ywRqSsgdSqbForm.getJhwcsj();//计划完成时间
		String jhsssjTemp = "";
		String jhwcsjTemp = "";
		if(jhsssj!=null){
			jhsssjTemp = DateUtils.dateTimeToString(jhsssj, DateUtils.YEAR_MOUTH_DAY_);
		}
		
		if(jhwcsj!=null){
			jhwcsjTemp = DateUtils.dateTimeToString(jhwcsj, DateUtils.YEAR_MOUTH_DAY_);
		}
		String knsyxqy = ywRqSsgdSqbForm.getKnsyxqy();//可能受影响区域
		if(StringUtils.isEmpty(knsyxqy)){
			knsyxqy = "";
		}
		String knsyxyh = ywRqSsgdSqbForm.getKnsyxyh();//可能受影响用户
		if(StringUtils.isEmpty(knsyxyh)){
			knsyxyh = "";
		}
		String lxrtel = ywRqSsgdSqbForm.getYwlxrtel();//申请单位-联系电话
		Locale locale = Locale.getDefault(); 
    	ResourceBundle localResource = ResourceBundle.getBundle("interfaceExchange", locale); 
    	String spdwdh = ywRqSsgdSqbForm.getSpdwdh();
    	if(StringUtils.isEmpty(spdwdh)){
    		spdwdh = localResource.getString("spdwdh");//公示表中的审批单位  电话
    	}
    		
		String spdwtel = spdwdh;//审批单位电话
		Date gskssj = ywRqSsgdSqbForm.getGskssj();//公示开始时间
		Date gsjssj = ywRqSsgdSqbForm.getGsjssj();//公示结束时间
		String gskssjStr = "";
		String gsjssjStr = "";
		if(gskssj != null){
			gskssjStr = DateUtils.dateTimeToString(gskssj, DateUtils.YEAR_MOUTH_DAY_);
		}
		if(gsjssj != null){
			gsjssjStr = DateUtils.dateTimeToString(gsjssj, DateUtils.YEAR_MOUTH_DAY_);
		}
		String acceptNo = ywRqSsgdSqbForm.getAcceptNo();
		String publicTablePath = localResource.getString("publicTablePath");
		String filePath = publicTablePath+acceptNo+".html";
		File file = new File(filePath);
//		File file = new File("d:\\aaa.html");
		//你可在这写c:\\abc.html 这样就是不同的文件了
		FileWriter fw;
		fw = new FileWriter(file);
		StringBuffer sb = new StringBuffer();
		sb.append("<div id='tpanel04' align='center'><br/><b>广州市燃气设施改动行政许可审批公示表</b> <br/> <br/><table class='font' ");
		sb.append(" width='700px' align='center' border='1px' bordercolor='#000000' cellspacing='0px'><tr style='display:none'><td colspan='10'>&nbsp;</td></tr><tr><td bordercolor='#000000' ");
		sb.append(" colspan='2' height='25' align='center' width='900px'>公示项目名称</td><td colspan='8' bordercolor='#000000' style='padding: 1px 1px 1px 1px;'>"+ssgdmc+"</td></tr><tr><td ");
		sb.append(" bordercolor='#000000' colspan='2' height='25' align='center'>公示开始时间</td><td colspan='3' width='30%' bordercolor='#000000' style='padding:");
		sb.append("1px 1px 1px 1px;'>"+gskssjStr+"</td><td bordercolor='#000000' colspan='2' height='25' align='center'>公示结束时间</td><td colspan='3' width='30%' ");
		sb.append("bordercolor='#000000' style='padding: 1px 1px 1px 1px;'>"+gsjssjStr+"</td></tr><tr><td bordercolor='#000000' colspan='2' height='25' align='center'>项目地点</td><td ");
		sb.append(" colspan='4' bordercolor='#000000' style='padding: 1px 1px 1px 1px;'>"+address+"</td><td bordercolor='#000000' colspan='2' height='25' align='center' width='400px'>所属行政区域</td><td ");
		sb.append("colspan='2' bordercolor='#000000' style='padding: 1px 1px 1px 1px;'>"+itemName+"</td></tr><tr><td bordercolor='#000000' colspan='2' height='25' align='center'>项目主要内容");
		sb.append("</td><td colspan='8' bordercolor='#000000' style='padding: 1px 1px 1px 1px;'>"+gdzynr+"</td></tr><tr><td bordercolor='#000000' colspan='2' height='25' align='center'>设");
		sb.append("施改动原因</td><td colspan='8' bordercolor='#000000' style='padding: 1px 1px 1px 1px;'>"+ssgdyy+"</td></tr><tr><td bordercolor='#000000' colspan='2' height='25' ");
		sb.append("align='center'>计划开工时间</td><td colspan='4' bordercolor='#000000' style='padding: 1px 1px 1px 1px;'>"+jhsssjTemp+"</td><td bordercolor='#000000' colspan='2' height='25' ");
		sb.append("align='center'>计划完工时间</td><td colspan='2' bordercolor='#000000' style='padding: 1px 1px 1px 1px;'>"+jhwcsjTemp+"</td></tr><tr><td bordercolor='#000000' colspan='2' ");
		sb.append("height='25' align='center'>可能受影响区域</td><td colspan='8' bordercolor='#000000' style='padding: 1px 1px 1px 1px;'>"+knsyxqy+"</td></tr><tr><td bordercolor='#000000'");
		sb.append("colspan='2' height='25' align='center'>可能受影响用户</td><td colspan='8' bordercolor='#000000' style='padding: 1px 1px 1px 1px;'>"+knsyxyh+"</td></tr><tr><td ");
		sb.append("bordercolor='#000000' colspan='2' height='25' rowspan='2' align='center'>咨询电话</td><td bordercolor='#000000' colspan='4' height='25' align='center'>申请单位");
		sb.append("</td><td colspan='4' bordercolor='#000000' style='padding: 1px 1px 1px 1px;'>"+lxrtel+"</td></tr><tr><td bordercolor='#000000' colspan='4' height='25' ");
		sb.append("align='center'>审批单位</td><td colspan='4' bordercolor='#000000' style='padding: 1px 1px 1px 1px;'>"+spdwtel+"</td></tr>");
		sb.append("</table></div>");
//			System.out.println("------------------->>"+sb.toString());
		fw.write(sb.toString());
        fw.flush();
        fw.close();
        //上传到另外一台机器
//		SFTPUtil.uploadOtherFileForFx(filePath, filePath);
	
	}
	
	

	//------------------------------------------------------公共部分
	
	/**
	 * 通知书标签与值对应map  公共方法
	 * @param approvalNo                      	预受理号,必填
	 * @param acceptNo                        	受理号,必填
	 * @param businessCode					  	业务代码，必填
	 * @param sqdw								申请单位，必填
	 * @param cbyw								承办业务，必填
	 * @param task								WfBusInstanceTaskForm
	 * @param loginUserName						登录用户名
	 * @param dpm								部门
	 * @param thisNoteActivityName				
	 * @param thisNoteActivityChineseName		受理状态(参见附录),必填
	 * @param notice							受理通知书字段，xml格式
	 * @param acceptTime						受理时间
	 * @return  map
	 */
	public Map<String, String> getCommonNoticeLabel(String approvalNo,String acceptNo,String businessCode,String applyUnitName, String applyAcceptName,
			WfBusInstanceTaskForm task, String loginUserName, String dpm, String thisNoteActivityName,String thisNoteActivityChineseName, String notice,Date acceptTime){
		try {
			String approvalInfo = task.getHandleComments();// 
			if(StringUtils.isEmpty(approvalInfo)){
				approvalInfo = "";
			}else{
				approvalInfo = StringUtilsEX.formatStr(approvalInfo);
			}
			String approvalNotice = notice;// 
			String approvalStatus = thisNoteActivityChineseName;
			Date date = new Date();
			String acceptTimeStr = DateUtils.dateTimeToString(acceptTime);// 受理时间，必填，格式yyyy-MM-dd
			// hh:mm:ss
			String acceptLimitDate = "";// 受理时限，必填
			String isAccept = "1";// 是否受理,必填，1为已受理，0为不受理
			String isDelay = "0";// 是否延期，必填, 1为是，0为否
			String delayTime = "";// 延迟时间, 格式yyyy-MM-dd hh:mm:ss
			String finishTime = "";
			String publicTable = "";
			if("ajgs".equals(thisNoteActivityName)){//案件公示环节，则把publicTable值放进去
				publicTable = acceptNo+".html";
				approvalStatus = "案件公示";
			}
			/*
			 * if(StringUtils.isNotEmpty(form.getJarq().toString())){ finishTime =
			 * DateUtils.dateTimeToString(form.getJarq());//结案时间, 格式yyyy-MM-dd
			 * hh:mm:ss }
			 */
			String auditTime = DateUtils.dateTimeToString(date);// 审核时间,必填
			String auditUser = loginUserName;// 审核人员,必填
			String auditDept = dpm;// 审核部门,必填
			String qu = "";//市、区的标志
			if(StringUtils.isNotBlank(task.getTemplateCode()) && task.getTemplateCode().contains("qx")){
				qu = "区";
			}else{
				qu = "市";
			}

			noticeLabelMap = new HashMap<String, String>();
			noticeLabelMap.put("approvalNo", approvalNo);
			noticeLabelMap.put("acceptNo", acceptNo);
			noticeLabelMap.put("businessCode", businessCode);
			noticeLabelMap.put("approvalStatus", approvalStatus);
			noticeLabelMap.put("approvalInfo", approvalInfo);
			noticeLabelMap.put("approvalNotice", approvalNotice);
			noticeLabelMap.put("applyUnitName", applyUnitName);
			noticeLabelMap.put("applyAcceptName", applyAcceptName);
			noticeLabelMap.put("acceptTime", acceptTimeStr);
			noticeLabelMap.put("acceptLimitDate", acceptLimitDate);
			noticeLabelMap.put("isAccept", isAccept);
			noticeLabelMap.put("isDelay", isDelay);
			noticeLabelMap.put("delayTime", delayTime);
			noticeLabelMap.put("finishTime", finishTime);
			noticeLabelMap.put("publicTable", publicTable);
			noticeLabelMap.put("auditTime", auditTime);
			noticeLabelMap.put("auditUser", auditUser);
			noticeLabelMap.put("auditDept", auditDept);
			noticeLabelMap.put("qu", qu);
		} catch (RuntimeException e) {
			logger.error(acceptNo+"产生noticeLabelMap异常"+SysTraceLogWriter.MESSAGE_SEPARATOR + e.getMessage(), e);
			e.printStackTrace();
		}
		return noticeLabelMap;
	
	}
	
	/**
	 * 获取审批的状态
	 * @return 状态status
	 */
	public String getStatus(String thisNoteActivityName) {
		String status = "";
		Locale locale = Locale.getDefault(); 
		ResourceBundle localResource = ResourceBundle.getBundle("noteStatus", locale); 
    	status = localResource.getString(thisNoteActivityName);//获取流程节点名称对应的状态
		return status;
	}

	
	/**
	 * 发送通知书 2
	 * @param YwRqSsgdSqbForm ywRqSsgdSqbForm
	 * @param WfBusInstanceTaskForm instance
	 * @param loginUserName
	 * @param dpm
	 */
	public void sendNotice2(Map<String,String> noticeLabelMap) {
		// 发送通知书
		//callWebServiceImpl.callWebService2(noticeLabelMap);
	}

	/**
	 * 产生通知的 字符串
	 * @param noticeLabelMap 标签的键值map
	 * @return 公共部分的字符串 para
	 */
	public String createNotice(Map<String, String> noticeLabelMap) {
		String approvalNo = noticeLabelMap.get("approvalNo");// 预受理号,必填
		String acceptNo = noticeLabelMap.get("acceptNo");// 受理号,必填
		String businessCode = noticeLabelMap.get("businessCode");// 业务代码，必填
		String approvalStatus = noticeLabelMap.get("approvalStatus");// 受理状态(参见附录),必填

		String approvalInfo = noticeLabelMap.get("approvalInfo");// 受理意见,必填
		if(StringUtils.isEmpty(approvalInfo)){
			approvalInfo = "";
		}else{
			approvalInfo = StringUtilsEX.formatStr(approvalInfo);
		}
		String approvalNotice = noticeLabelMap.get("approvalNotice");// 受理通知书字段，xml格式
		String applyUnitName = noticeLabelMap.get("applyUnitName");// 申请单位，必填
		String applyAcceptName = noticeLabelMap.get("applyAcceptName");// 受理事项，必填

		String acceptTime = noticeLabelMap.get("acceptTime");// 受理时间，必填，格式yyyy-MM-dd
		// hh:mm:ss
		String acceptLimitDate = noticeLabelMap.get("acceptLimitDate");// 受理时限，必填
		String isAccept = noticeLabelMap.get("isAccept");// 是否受理,必填，1为已受理，0为不受理
		String isDelay = noticeLabelMap.get("isDelay");// 是否延期，必填, 1为是，0为否
		String delayTime = noticeLabelMap.get("delayTime");// 延迟时间,
		// 格式yyyy-MM-dd
		// hh:mm:ss
		String finishTime = noticeLabelMap.get("finishTime");
		if(StringUtils.isBlank(finishTime)){
			finishTime=this.getEndDate(acceptNo);
		}
		if(StringUtils.isBlank(finishTime)){
			finishTime = "";
		}
		/*
		 * if(StringUtils.isNotEmpty(form.getJarq().toString())){ finishTime =
		 * DateUtils.dateTimeToString(form.getJarq());//结案时间, 格式yyyy-MM-dd
		 * hh:mm:ss }
		 */
		String auditTime = noticeLabelMap.get("auditTime");// 审核时间,必填
		String auditUser = noticeLabelMap.get("auditUser");// 审核人员,必填
		String auditDept = noticeLabelMap.get("auditDept");// 审核部门,必填
		String publicTable = noticeLabelMap.get("publicTable");//案件公示表html文件名称
		String qu = noticeLabelMap.get("qu");//市、区标志

		StringBuffer sb = new StringBuffer();
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		sb.append("<feedback>");
		sb.append("<approvalNo>" + approvalNo + "</approvalNo>");
		sb.append("<acceptNo>" + acceptNo + "</acceptNo>");
		sb.append("<businessCode>" + businessCode + "</businessCode>");
		sb.append("<approvalStatus>" + approvalStatus + "</approvalStatus>");
		sb.append("<approvalInfo>" + approvalInfo + "</approvalInfo>");
		sb.append("<approvalNotice>" + approvalNotice + "</approvalNotice>");
		sb.append("<applyUnitName>" + applyUnitName + "</applyUnitName>");
		sb.append("<applyAcceptName>" + applyAcceptName + "</applyAcceptName>");
		sb.append("<acceptTime>" + acceptTime + "</acceptTime>");
		sb.append("<acceptLimitDate>" + acceptLimitDate + "</acceptLimitDate>");
		sb.append("<isAccept>" + isAccept + "</isAccept>");
		sb.append("<isDelay>" + isDelay + "</isDelay>");
		sb.append("<delayTime>" + delayTime + "</delayTime>");
		sb.append("<finishTime>" + finishTime + "</finishTime>");
		sb.append("<publicTable>" + publicTable + "</publicTable>");
		sb.append("<auditTime>" + auditTime + "</auditTime>");
		sb.append("<auditUser>" + auditUser + "</auditUser>");
		sb.append("<auditDept>" + auditDept + "</auditDept>");
		sb.append("<qu>" + qu + "</qu>");
		sb.append("</feedback>");
		System.out.println("sb--------- "+sb.toString());
		String para = "";
		Base64 base64 = new Base64();
		try {
			para = new String(base64.encode(sb.toString().getBytes("UTF-8")));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return para;
	}
	
	
	/**
	 * 设置结案时间
	 * @param info
	 */
	private String getEndDate(String acceptNo){
		String enddate=null;
		//从 JBPM4_HIST_PROCINST表中取出结案时间
		if(StringUtils.isNotBlank(acceptNo)){
			String hql=" select proc.end from WfBusInstance ins,Jbpm4HistProcinst proc where " +
			" ins.procInstId=proc.procInstId and ins.busMemo3='"+acceptNo+"'";
			List lists=this.wfBusInstanceDao.find(hql);
			if(lists.size()>0){
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
				try {
					if(lists.get(0)!=null){
						Date endDate=(Date) lists.get(0);
						enddate=sdf.format(endDate);
					}
					
				} catch (RuntimeException e) {
					e.printStackTrace();
				}
			}
		}
		return enddate;
	}
	
	
	/**
	 * 产生结束公示的 字符串
	 * @param acceptNo
	 * @return 结束公示的 字符串 para
	 */
	public String createStopPublicXMLString(String acceptNo) {
		StringBuffer sb = new StringBuffer();
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		sb.append("<feedback>");
		sb.append("<acceptNo>" + acceptNo + "</acceptNo>");
		sb.append("</feedback>");
		String para = "";
		Base64 base64 = new Base64();
		try {
			para = new String(base64.encode(sb.toString().getBytes("UTF-8")));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return para;
	}
	
	/**
	 * 获得webservice所需要的参数
	 * @return
	 */
	public List getWebServicePara(){
		List list = new ArrayList();
		List resultList = ywWebserviceInfoService.getNoticeYwWebserviceInfo();
		for(int i = 0;i<resultList.size();i++){
			List paraList = new ArrayList();
			YwWebserviceInfo ywWebserviceInfo = (YwWebserviceInfo)resultList.get(i);
			String wsdl = ywWebserviceInfo.getWsdlPara();
			String SPXT_ApprovalInfoFeedBack_Service = ywWebserviceInfo.getParaTwo();
			String feedBackApprovalInfo = ywWebserviceInfo.getParaThree();
			String xmlStr = ywWebserviceInfo.getXmlStr();
			String acceptNo = ywWebserviceInfo.getAcceptNo();
			String approvalNo = ywWebserviceInfo.getParaFour();
			long id = ywWebserviceInfo.getId();
//			String filePath = ywWebserviceInfo.getFilePath();	
//			BufferedReader br = null;
//			try {
//				br = br = new BufferedReader(new FileReader(filePath));
//			} catch (FileNotFoundException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			String text; 
//			StringBuffer sb = new StringBuffer();
//			try {
//				while((text=br.readLine())!=null) {
//					sb = sb.append(text);
//				}
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			String para = sb.toString();
			paraList.add(wsdl);
			paraList.add(SPXT_ApprovalInfoFeedBack_Service);
			paraList.add(feedBackApprovalInfo);
			paraList.add(xmlStr);
			paraList.add(id);
			paraList.add(acceptNo);
			paraList.add(approvalNo);
			list.add(paraList);
		}
		return list;
	}
}
